package com.mengxinya.ys.social.wechatplatform;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 微信公众号接入
 * 注解使用servlet 需要在Application上加入 @ServletComponentScan
 */
@WebServlet(name="mpServlet",urlPatterns="/mp/api")
@Slf4j
public class WechatPlatformServlet extends HttpServlet {
    private final WechatPlatformService wechatPlatformService;

    public WechatPlatformServlet(WechatPlatformService wechatPlatformService) {
        this.wechatPlatformService = wechatPlatformService;
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String echostr = request.getParameter("echostr");

        WechatConnectVo connectVo = new WechatConnectVo(signature, timestamp, nonce, echostr);

        if (!wechatPlatformService.checkSignature(connectVo)) {
            log.info("非法请求");
            response.getWriter().println("非法请求");
            return;
        }

        // 说明是一个仅仅用来验证的请求，回显echostr
        if (StringUtils.isNotBlank(echostr)) {
            log.info("接入成功");
            response.getWriter().println(echostr);
            return;
        }

        String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ?
                "raw" :
                request.getParameter("encrypt_type");

        if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            String msgSignature = request.getParameter("msg_signature");

            List<WechatPlatformHandler> handlers = new ArrayList<>();

            String message = wechatPlatformService.service(request.getInputStream(), handlers, timestamp, nonce, msgSignature);
            response.getWriter().write(message);
            return;
        }

        response.getWriter().println("不可识别的加密类型");
    }

}
